<template>
  <div class="app-container">
    <!-- 查询区域 -->
    <el-form :model="queryParams" ref="queryRef" :inline="true" class="mb-4">
      <el-form-item label="服务类型" prop="serviceType">
        <el-select v-model="queryParams.serviceType" placeholder="请选择服务类型" clearable style="width: 200px">
          <el-option label="Service" :value="1" />
          <el-option label="Launcher" :value="2" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery" :loading="loading">查询</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
        <el-button type="success" icon="Upload" @click="handleUpdate">更新</el-button>
      </el-form-item>
    </el-form>

    <!-- 应用信息显示区域 -->
    <el-card v-if="appInfo" class="mt-4">
      <template #header>
        <div class="card-header">
          <span>应用信息</span>
        </div>
      </template>
      
      <el-form :model="appInfo" label-width="120px" class="app-info-form">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="应用名称">
              <el-input v-model="appInfo.name" readonly />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="包名">
              <el-input v-model="appInfo.packageName" readonly />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="版本号">
              <el-input v-model="appInfo.versionCode" readonly />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="版本名称">
              <el-input v-model="appInfo.versionName" readonly />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="应用图标">
                <el-input v-model="appInfo.icon" readonly />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="图标路径">
              <el-input v-model="appInfo.iconPath" readonly />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="最低SDK版本">
              <el-input v-model="appInfo.minSdkVersion" readonly />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="目标SDK版本">
              <el-input v-model="appInfo.targetSdkVersion" readonly />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </el-card>

    <!-- 无数据提示 -->
    <el-empty v-if="!appInfo && hasSearched" description="未找到相关应用信息" />

    <!-- 更新APK对话框 -->
    <el-dialog :title="'更新APK文件'" v-model="updateDialogVisible" width="500px" append-to-body>
      <el-form ref="updateFormRef" :model="updateForm" :rules="updateRules" label-width="100px">
        <el-form-item label="服务类型" prop="updateType">
          <el-select v-model="updateForm.updateType" placeholder="请选择服务类型" style="width: 100%">
            <el-option label="Service" :value="1" />
            <el-option label="Launcher" :value="2" />
          </el-select>
        </el-form-item>
        <el-form-item label="APK文件" prop="file">
          <el-upload
            ref="uploadRef"
            v-model:file-list="fileList"
            :auto-upload="false"
            :on-change="handleFileChange"
            :on-remove="handleFileRemove"
            :limit="1"
            accept=".apk"
            drag
          >
            <el-icon class="el-icon--upload"><upload-filled /></el-icon>
            <div class="el-upload__text">
              将APK文件拖到此处，或<em>点击上传</em>
            </div>
            <template #tip>
              <div class="el-upload__tip">
                只能上传APK文件
              </div>
            </template>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="updateDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="submitUpdate" :loading="updateLoading">确 定</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 修改图标对话框 -->
    <el-dialog :title="'修改应用图标'" v-model="iconDialogVisible" width="400px" append-to-body>
      <el-form ref="iconFormRef" :model="iconForm" :rules="iconRules" label-width="80px">
        <el-form-item label="图标路径" prop="iconPath">
          <el-input v-model="iconForm.iconPath" placeholder="请输入图标路径" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="iconDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="submitIconUpdate">确 定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Box">
import { ref, reactive } from 'vue'
import { getBoxApkInfo, updateBoxApkInfo } from '@/api/system/box'
import { ElMessage } from 'element-plus'
import { UploadFilled } from '@element-plus/icons-vue'

// 查询参数
const queryParams = reactive({
  serviceType: ''
})
const fileList = ref([])
// 应用信息
const appInfo = ref(null)
const hasSearched = ref(false)
const loading = ref(false)

// 更新相关
const updateDialogVisible = ref(false)
const updateLoading = ref(false)
const updateForm = reactive({
  updateType: '',
  file: null
})

const updateRules = {
  updateType: [{ required: true, message: '请选择服务类型', trigger: 'change' }],
  file: [{ required: true, message: '请选择APK文件', trigger: 'change' }]
}

// 图标修改相关
const iconDialogVisible = ref(false)
const iconForm = reactive({
  iconPath: ''
})

const iconRules = {
  iconPath: [{ required: true, message: '请输入图标路径', trigger: 'blur' }]
}

// 查询按钮操作
async function handleQuery() {
  if (!queryParams.serviceType) {
    ElMessage.warning('请选择服务类型')
    return
  }
  
  hasSearched.value = true
  loading.value = true
  
  try {
    const response = await getBoxApkInfo(queryParams.serviceType)
    if (response.code === 200) {
      appInfo.value = response.data
    } else {
      appInfo.value = null
      ElMessage.error(response.msg || '查询失败')
    }
  } catch (error) {
    console.error('查询失败:', error)
    appInfo.value = null
    ElMessage.error('查询失败，请稍后重试')
  } finally {
    loading.value = false
  }
}

// 重置按钮操作
function resetQuery() {
  queryParams.serviceType = ''
  appInfo.value = null
  hasSearched.value = false
}

// 更新按钮操作
function handleUpdate() {
  updateForm.updateType = ''
  updateForm.file = null
  fileList.value = []
  updateDialogVisible.value = true
}

// 上传组件引用
const uploadRef = ref()

// 文件选择处理
function handleFileChange(file) {
  updateForm.file = file.raw
}

// 文件移除处理
function handleFileRemove() {
  updateForm.file = null
}

// 提交更新
async function submitUpdate() {
  if (!updateForm.updateType) {
    ElMessage.warning('请选择服务类型')
    return
  }
  
  if (!updateForm.file) {
    ElMessage.warning('请选择APK文件')
    return
  }
  
  updateLoading.value = true
  
  try {
    const formData = new FormData()
    formData.append('file', updateForm.file)
    formData.append('type', updateForm.updateType)
    
    const response = await updateBoxApkInfo(formData)
    if (response.code === 200) {
      ElMessage.success('更新成功')
      updateDialogVisible.value = false
      // 清空表单数据
      updateForm.updateType = ''
      updateForm.file = null
      // 清空上传组件
      if (uploadRef.value) {
        uploadRef.value.clearFiles()
      }
      // 重新查询当前显示的信息
      if (appInfo.value) {
        await handleQuery()
      }
    } else {
      ElMessage.error(response.msg || '更新失败')
    }
  } catch (error) {
    console.error('更新失败:', error)
    ElMessage.error('更新失败，请稍后重试')
  } finally {
    updateLoading.value = false
    fileList.value = []
  }
}

// 修改图标
function modifyIcon() {
  iconForm.iconPath = appInfo.value.icon || ''
  iconDialogVisible.value = true
}

// 提交图标修改
function submitIconUpdate() {
  if (appInfo.value) {
    appInfo.value.icon = iconForm.iconPath
    ElMessage.success('图标路径已更新')
    iconDialogVisible.value = false
  }
}
</script>

<style scoped>
.mb-4 {
  margin-bottom: 16px;
}

.mt-4 {
  margin-top: 16px;
}

.ml-2 {
  margin-left: 8px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.app-info-form .el-form-item {
  margin-bottom: 18px;
}

.icon-display {
  display: flex;
  align-items: center;
}

.dialog-footer {
  text-align: right;
}
</style>
 